import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { LoginService } from '../services/login/login.service';
import { loginModel } from './login.model';
import { OAuthService } from 'angular-oauth2-oidc';
// import { LOGININFO } from './../config';
import { LOGININFO, qrCodeUrl } from '@src/app/config';
import { ActiveDescendantKeyManager } from '@angular/cdk/a11y';
import { Abp } from '@zzj/zzj-abp-web';

declare var CryptoJS: any;

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})

export class LoginComponent implements OnInit {
  @ViewChild('userNameOrEmailAddress', { static: false }) userNameOrEmailAddress;
  @ViewChild('password', { static: false }) password;
  // @ViewChild('code') code;

  constructor(
    private router: Router,
    private loginService: LoginService,
    private fb: FormBuilder,
    private message: NzMessageService,
    private oauthService: OAuthService
  ) { }

  validateForm: FormGroup;
  tenantId: any = '';
  remenberLogin = false;
  isLoading = false;
  qrCodeUrl = `../../assets/images/QRcode/${qrCodeUrl}.png`;

  /**
   * 初始化
   */
  async init() {
    // 令牌
    const result = await this.loginService.isTenantAvailable({ tenancyName: 'Default' });
    this.tenantId = result.result.tenantId;
    console.log(result.result.tenantId);

    // 获取文件服务token 并储存 进sessionStorage
    // this.loginService.getTokenInfo().then((access_token) => {
    //   console.log(access_token.result.access_token)
    //   sessionStorage.setItem('access_token', access_token.result.access_token)
    // });
  }

  /**
   * 登录
   */
  login() {
    //  console.log(this.submitForm())
    this.throttle(this.submitForm(), 1000);
  }


  async submitForm() {

    await this.init();
    if (!this.validateForm.value.userNameOrEmailAddress) {
      this.message.warning('请输入用户名');
      this.userNameOrEmailAddress.nativeElement.focus();
      return;
    } else if (!this.validateForm.value.password) {
      this.message.warning('请输入密码');
      this.password.nativeElement.focus();
      return;
    }


    const loginInfo = this.validateForm.value;
    const json = {
      tenancyName: 'Default',
      userNameOrEmailAddress: loginInfo.userNameOrEmailAddress,
      password: CryptoJS.MD5(loginInfo.password).toString().toUpperCase(),
      type: 1
    };
    const params = new loginModel(json);
    const headers = { 'X-Requested-With': 'XMLHttpRequest' };
    headers['Abp.TenantId'] = this.tenantId;
    // 登录接口
    if (!this.isLoading) {
      const result = await this.loginService.apiLogin(params, headers);
      this.isLoading = true;
      // console.log(result)
      if (result.error) {
        this.message.warning(result.error.details);
        this.isLoading = false;
        return;
      }
      // 记录企业Id
      await window.localStorage.setItem('organizationUnitId', JSON.stringify(result.result.organizationUnitId));
      // 记录TenantId
      await window.localStorage.setItem('TenantId', JSON.stringify(this.tenantId));
      // 记录token
      await window.localStorage.setItem('APDInfo', JSON.stringify(result.result));
      // 企业ID
      await window.localStorage.setItem('PrimaryId', result.result.primaryId);
      // 获取spd token
      if (result.success) {
        this.loginService.getTokenInfo().then((access_token) => {
          console.log(access_token.result.access_token);
          sessionStorage.setItem('access_token', access_token.result.access_token);
        });
      }
    }




    // 权限
    await this.loginService.getAll().then((res) => {
      // console.log(res)
      const result = res.result;
      const auth = result.auth;
      const allPermissions = auth.allPermissions;
      const grantedPermissions = auth.grantedPermissions;
      const platform = result.localization.values.Platform;
      Abp.auth.setGlobal(result.auth);
      // 记录当前用户企业级权限
      window.localStorage.setItem('Abp.grantedPermissions', JSON.stringify(grantedPermissions));
      // 记录所有权限
      window.localStorage.setItem('Abp.allPermissions', JSON.stringify(allPermissions));
      // 记录权限对应中文
      window.localStorage.setItem('Abp.platform', JSON.stringify(platform));

    });

    this.isLoading = false;
    // 路由
    this.routerTo();
  }

  /**
   * 路由
   */
  routerTo() {
    this.router.navigate([`outer/project-type`]);
  }

  // 登录节流
  throttle(fn, delay) {
    // debugger;
    let valid = true;
    return function () {
      if (!valid) {
        // 休息时间 暂不接客
        return false;
      }
      // 工作时间，执行函数并且在间隔期内把状态位设为无效
      valid = false;
      setTimeout(() => {
        // tslint:disable-next-line: no-unused-expression
        fn;
        valid = true;
      }, delay);
    };
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      userNameOrEmailAddress: [null, [Validators.required]],
      password: [null, [Validators.required]],
      code: [null, [Validators.required]]
    });
  }

  // tslint:disable-next-line: use-life-cycle-interface
  ngAfterViewInit() {
    this.userNameOrEmailAddress.nativeElement.focus();
  }
}
